// 客户组ID
var mainCustomerId = sessionStorage.getItem("mainCustomerId");

//页大小
var pageSize = 50;

$(function () {
    var projectCode = sessionStorage.getItem("projectCode");
    console.log(projectCode);
    if (projectCode) {
        queryCustomerMappersById(projectCode);
    }
})

//跳转
function skipPage (title, url) {
    var index = layer.open({
        type: 2,
        title: title,
        offset: 't',
        area: ["1080px", "800px"],
        content: url
    });
    layer.restore(index);
}

//选择项目-列表
function screenProjectPageList () {
    $("#screenProject-modal").modal('show');

    var json = {
        mappingStatus: 0,
        mainCustomerId: mainCustomerId,
        projectCode: $("input[name='projectCode']").val(),
        projectName: $("input[name='projectName']").val(),
        pageNum: 1,
        pageSize: pageSize
    }
    $.ajax({
        url: root.projectMap.queryListPage,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(json),
        success: function (result) {
            screenProject_Shield(result);
            $('.M-box3-screenProject').pagination({
                pageCount: result.data.pageCount,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    json.pageNo = api.getCurrent();
                    $.ajax({
                        url: root.projectMap.queryListPage,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType: 'json',
                        contentType: "application/json",
                        data: JSON.stringify(json),
                        success: function (result) {
                            screenProject_Shield(result);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！', 2000);
        }
    });
}

//选择项目-列表-渲染
function screenProject_Shield (dataSource) {
    var dttable = $('#shanDataTable').dataTable(); // 初始化dataTable，清空上一个值
    dttable.fnClearTable(); //清空一下table
    dttable.fnDestroy(); //还原初始化了的datatable
    $("#shanDataTable").DataTable({
        "order": [[2, "desc"]],
        "autoWidth": false,
        "ordering": false,
        "searching": false,
        "paging": false,
        "retrieve": true,
        "destroy": true,
        "bAutoWidth": true,
        "bLengthChange": true,
        "aLengthMenu": [5, 10, 25, 50],
        "oLanguage": {
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "抱歉， 没有找到",
            "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
            "sInfoEmpty": "",
            "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            },
            "sZeroRecords": "没有检索到数据",
            "sProcessing": "<img src='./loading.gif' />",
        },
        data: dataSource.data.data,
        columnDefs: [
            {
                "render": function (data, type, row, meta) {
                    var val = row.id
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 0
            },
            {
                "render": function (data, type, row, meta) {
                    var val = row.projectName
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 1
            },
            {
                "render": function (data, type, row, meta) {
                    var val = row.subcompany
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 2
            },
            {
                "render": function (data, type, row) {
                    var val = "<a href='javascript:0;' onclick=\"writeBackPro(" + row.id + ",'" + row.projectCode + "','" + row.projectName + "','" + row.subcompany + "','" + row.contactPerson + "','" + row.contactPhone + "','" + row.address + "')\">选择</a> ";
                    return val;
                },
                "targets": 3
            },
        ]
    });
};

//回写项目
function writeBackPro (id, projectCode, projectName, subcompany, contactPerson, contactPhone, address) {
    $("input[name='id']").val(id);
    $("input[name='projectCode']").val(projectCode);
    $("input[name='projectName']").val(projectName);
    $("input[name='subcompany']").val(subcompany);
    $("input[name='contactPerson']").val(contactPerson);
    $("input[name='contactPhone']").val(contactPhone);
    $("input[name='address']").val(address);
    //$("input[name='projectState ']").val(projectState);
    $("#screenProject-modal").modal('hide');
}

//选择客户-列表
function screenCustomerPageList () {
    $("#screenCustomer-modal").modal('show');
    var json = {
        mainCustomerId: mainCustomerId,
        customerCode: $(".customerCode").val(),
        customerId: $(".customerId").val(),
        customerName: $(".customerName2").val(),
        pageNum: 1,
        pageSize: pageSize
    }
    $.ajax({
        url: root.member.getCustomers,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(json),
        success: function (result) {
            screenCustomer_Shield(result);
            $('.M-box3-screenCustomer').pagination({
                pageCount: result.data.pageCount,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    json.pageNo = api.getCurrent();
                    $.ajax({
                        url: root.member.getCustomers,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType: 'json',
                        contentType: "application/json",
                        data: JSON.stringify(json),
                        success: function (result) {
                            screenCustomer_Shield(result);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！', 2000);
        }
    });
}

//选择客户-列表-渲染
function screenCustomer_Shield (dataSource) {
    var dttable = $('#customerShanDataTable').dataTable(); // 初始化dataTable，清空上一个值
    dttable.fnClearTable(); //清空一下table
    dttable.fnDestroy(); //还原初始化了的datatable
    $("#customerShanDataTable").DataTable({
        "order": [[2, "desc"]],
        "autoWidth": false,
        "ordering": false,
        "searching": false,
        "paging": false,
        "retrieve": true,
        "destroy": true,
        "bAutoWidth": true,
        "bLengthChange": true,
        "aLengthMenu": [5, 10, 25, 50],
        "oLanguage": {
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "抱歉， 没有找到",
            "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
            "sInfoEmpty": "",
            "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            },
            "sZeroRecords": "没有检索到数据",
            "sProcessing": "<img src='./loading.gif' />",
        },
        data: dataSource.data.data,
        columnDefs: [
            {
                "render": function (data, type, row, meta) {
                    var val = row.customerId
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 0
            },
            {
                "render": function (data, type, row, meta) {
                    var val = row.customerCode
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 1
            },
            {
                "render": function (data, type, row, meta) {
                    var val = row.customerName
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 2
            },
            {
                "render": function (data, type, row, meta) {
                    var val = row.belongGroupName
                    if (val == undefined) {
                        val = ''
                    }
                    return val;
                },
                "targets": 3
            },
            {
                "render": function (data, type, row) {
                    var val = "<a href='javascript:0;' onclick=\"writeBackCustomer('" + row.customerCode + "','" + row.customerId + "','" + row.customerName + "','" + row.belongGroupName + "')\">选择</a> ";
                    return val;
                },
                "targets": 4
            },
        ]
    });
};

//回写客户
function writeBackCustomer (customerCode, customerId, customerName, belongGroupName) {
    $("input[name='customerId']").val(customerId);
    $("input[name='customerCode']").val(customerCode);
    $("input[name='customerName']").val(customerName);
    $("input[name='belongGroupName']").val(belongGroupName);
    $("#screenCustomer-modal").modal('hide');

}

//修改项目映射
function updateCustomerProjects () {
    var mappingStatus = $("input[name='mappingStatus']").val();
    var param = {
        mainCustomerId: mainCustomerId,
        insertOrUpdate: mappingStatus ? 1 : 0,
        id: $("input[name='id']").val(),
        mappingStatus: mappingStatus,
        projectState: $("input[name='projectState']").val(),
        crmCustomerCode: $("input[name='customerCode']").val(),
        crmCustomerId: $("input[name='customerId']").val(),
        crmCustomeName: $("input[name='customerName']").val(),
        crmCustomerBelong: $("input[name='belongGroupName']").val(),
        projectCode: $("input[name='projectCode']").val(),
        projectName: $("input[name='projectName']").val(),
        subcompany: $("input[name='subcompany']").val(),
        contactPerson: $("input[name='contactPerson']").val(),
        contactPhone: $("input[name='contactPhone']").val(),
        address: $("input[name='address']").val(),
        //projectState : $("input[name='projectState ']").val(),
    }
    $.ajax({
        url: root.projectMap.updateCustomerMapping,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(param),
        success: function (result) {
            if (result) {
                $.Huimodalalert(result.msg, 2000);
                if (result.code == 0) {
                    window.setTimeout(function () {
                        window.parent.location.reload();
                        parent.layer.closeAll();
                    }, 1000)
                }else{
                    $.Huimodalalert(result.msg, 2000);
                }
            } else {
                $.Huimodalalert("接口返回参数为null", 2000);
            }
        },
        error: function () {
            $.Huimodalalert('失败！', 2000);
        }
    });
}

//根据项目编码查询项目映射
function queryCustomerMappersById (projectCode) {
    var param = { projectCode:projectCode };
    $.ajax({
        url: root.projectMap.queryCustomerMappersById,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(param),
        success: function (result) {
            if (result.data) {
                $("input[name='id']").val(result.data.id);
                $("input[name='mappingStatus']").val(result.data.mappingStatus);
                $("input[name='projectState']").val(result.data.projectState);
                $("input[name='customerCode']").val(result.data.crmCustomerCode);
                $("input[name='customerId']").val(result.data.crmCustomerId);
                $("input[name='customerName']").val(result.data.crmCustomeName);
                $("input[name='belongGroupName']").val(result.data.crmCustomerBelong);
                $("input[name='projectCode']").val(result.data.projectCode);
                $("input[name='projectName']").val(result.data.projectName);
                $("input[name='subcompany']").val(result.data.subcompany);
                $("input[name='contactPerson']").val(result.data.contactPerson);
                $("input[name='contactPhone']").val(result.data.contactPhone);
                $("input[name='address']").val(result.data.address);
            }else{
                $.Huimodalalert('data数据为null', 2000);
            }
        },
        error: function () {
            $.Huimodalalert('失败！', 2000);
        }
    });
}

//重置项目列表
function screenProjectReset () {
    $(".projectCode").val("");
    $(".projectName").val("");
    screenProjectPageList();
}

//重置客户列表
function screenCustomerReset () {
    $(".customerCode").val("");
    $(".customerId").val("");
    $(".customerName2").val("");
    screenCustomerPageList();
}